<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class ReturnDecode extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rcrypt:d {ciphertext} {ts} ';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '解密前后端交互密文';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $data = $this->argument('ciphertext');
        $sKey = $this->argument('ts');

        $t = $data;
        $len = strlen($t);
        $per = intval($len/4);
        if($per<2){
            $len_key = strlen($sKey);
            $base64_estr = substr($t, 0, $len-$len_key);
            echo self::_base64UrlDecode($base64_estr);
            exit();
        }
        $i = 0;
        $t_len = $len;
        $arr_per_num = [];
        while(true){
            if($t_len/$per>1){
                $arr_per_num[] = $per;
            }else{
                break;
            }
            $t_len = $t_len - $per;
        }

        $arr_per = [];
        $t_start = 0;
        $t_count = count($arr_per_num);
        foreach($arr_per_num as $k=>$per){
            $t_start -= $per;
            $arr_per[$t_count-1-$k] = substr($t, $t_start, $per);
        }

        $last_str = substr($t, 0, $len+$t_start);
        //var_dump($last_str);

        $i = 0 ;
        $max = count($arr_per);
        $str = "";
        for($i=0; $i<$max; $i++){
            if(isset($arr_per[$i])){
                $str .= $arr_per[$i];
            }
        }
        //var_dump($str);
        $str .= $last_str;
        //echo "\n==============str======================\n";
        //echo "\n{$str}\n";
        $len_key = strlen($sKey);
        $str = substr($str, 0, $len-$len_key);
        echo self::_base64UrlDecode($str);
        exit();
    }

    /**
     * get传输的编码功能   因为客户端提交时，服务器自动url解码一次。base64的字符会被转换
     * @param unknown $data
     * @return string
     */
    private static function _base64UrlEncode($data)
    {
        $data = base64_encode($data);
        $data = strtr($data, '+/', '-_');
        // 默认情况下，取消对编码的填充，因为它不需要解码，并且保持URL不含%编码。
        $data = rtrim($data, '=');
        return $data;
    }

    /**
     * get传输的解码功能
     * @param unknown $data
     * @return string
     */
    private static function _base64UrlDecode($data)
    {
        $data = strtr($data, '-_', '+/');
        return base64_decode($data);
    }
}
